<template>
  <div v-loading="loadup" class="app-container">
    <div class="filter-container">
      <el-row :gutter="0">
        <el-form :inline="true" class="search-form">
          <!--<el-form-item label="">
            <el-input v-model="query.name" class="filter-item" placeholder="文件名" clearable/>
          </el-form-item>-->
          <el-form-item label="">
            <el-date-picker
              v-model="query.range_date"
              type="daterange"
              class="filter-item"
              style="width: 240px;"
              range-separator="-"
              value-format="yyyy-MM-dd"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button class="" type="primary" icon="el-icon-search" @click="search">查询</el-button>
            <el-button class="" type="success" icon="el-icon-refresh-right" plain @click="refresh()">刷新</el-button>
          </el-form-item>

          <el-form-item style="float: right">
            <el-upload
              name="file"
              :limit="uploadLimit"
              :file-list="uploadFilelist"
              :multiple="true"
              :show-file-list="false"
              :auto-upload="true"
              :action="uploadAction"
              :headers="uploadHeaders"
              :data="uploadData"
              :before-upload="uploadBefore"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :on-change="uploadChange"
              :on-exceed="uploadExceed"
            >
              <el-button type="primary" icon="el-icon-upload" @click="uploadClear">上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row :gutter="0" v-show="total > 0">
        <el-col :xs="24">
          <div class="left-panel">
            <el-checkbox v-model="checkAll" class="filter-item" size="mini" border style="margin-right: 10px" :indeterminate="checkAllInd" @change="selectAll">全选</el-checkbox>
            <el-button class="filter-item" type="info" size="mini" plain @click="isActivate(checkedIds, 1)">启用</el-button>
            <el-button class="filter-item" type="warning" size="mini" plain @click="isActivate(checkedIds, 0)">禁用</el-button>
            <el-button class="filter-item" type="danger" size="mini" plain icon="el-icon-delete" @click="batchDel(checkedIds)">批量删除</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-row :gutter="3">
      <!-- 筛选 -->
      <el-col :span="4" class="">
        <el-card class="box-card">
          <div class="text item">文件夹：</div>
          <div class="text item">
            <el-link :type="query.folder===''?'primary':''" :underline="false" style="height:26px;" @click="filterSelect('', query.file_type)">全部</el-link>
          </div>
          <div v-for="folder in folders" :key="folder" class="text item">
            <el-link :type="query.folder===folder?'primary':''" :underline="false" @click="filterSelect(folder, query.file_type)">{{ folder }}</el-link>
          </div>

          <div class="text item" style="margin-top: 20px">类型：</div>
          <div class="text item">
            <el-link :type="query.file_type===''?'primary':''" :underline="false" style="height:26px;" @click="filterSelect(query.folder, '')">全部</el-link>
          </div>
          <div v-for="(item, index) in fileTypes" :key="index" class="text item">
            <el-link :type="query.file_type===index?'primary':''" :underline="false" style="height:26px;" @click="filterSelect(query.folder, index)">{{ item }}</el-link>
          </div>
        </el-card>
      </el-col>
      <!-- 列表 -->
      <el-col v-if="total > 0" :span="20" class="dialog-body" :style="{height:height-45+'px'}">
        <el-row :gutter="3">
          <el-checkbox-group v-model="checkedIds" @change="selectGroup">
            <el-col v-for="(item, index) in datas" :key="index" :span="4" style="margin-bottom:6px; text-align:center">
              <el-card class="file-card" :body-style="{ minWidth:'16.5%', padding:'0 6px' }">
                <div class="file-ext">
                  <span>{{ item.file_ext }}</span>
                </div>
                <div style="text-align:left">
                  <el-checkbox :key="item.id" :label="item.id"/>
                </div>
                <div :style="{width:'100%', height:((height-height*0.1)/3)-((height-height*0.1)/3*0.45)+'px'}">
                  <el-image v-if="item.file_type==='image'" fit="contain" :src="item.full_file_url" :preview-src-list="[item.full_file_url]" style="height:100%;"/>
                  <video v-else-if="item.file_type==='video'" width="100%" height="100%" controls>
                    <source :src="item.full_file_url" type="video/mp4">
                    <object :data="item.full_file_url" width="100%" height="100%">
                      <embed :src="item.full_file_url" width="100%" height="100%">
                    </object>
                  </video>
                  <audio v-else-if="item.file_type==='audio'" width="100%" height="100%" controls>
                    <source :src="item.full_file_url" type="audio/mp3">
                    <embed :src="item.full_file_url" width="100%" height="100%">
                  </audio>
                  <el-image v-else-if="item.file_type==='word'" :src="item.file_url" style="width:100%; height:100%;">
                    <div slot="error" class="image-slot">
                      <i class="el-icon-document" style="font-size:50px"/>
                    </div>
                  </el-image>
                  <el-image v-else :src="item.full_file_url" style="width:100%; height:100%;">
                    <div slot="error" class="image-slot">
                      <i class="el-icon-folder" style="font-size:50px"/>
                    </div>
                  </el-image>
                </div>
                <div style="padding-top:6px;">
                  <span style="font-size:14px;">{{ item.file_size }}</span>
                  <div class="bottom clearfix">
                    <el-button v-if="item.file_type == 'video'" type="text" size="mini" @click="viewVideo(item.full_file_url)">查看</el-button>
                    <el-button v-if="!item.status" type="text" size="mini" @click="isActivate([item.id], 1)">启用</el-button>
                    <el-button v-else type="text" size="mini" @click="isActivate([item.id], 0)">禁用</el-button>
                    <el-button size="mini" type="text" @click="del([item.id])">删除</el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-checkbox-group>
        </el-row>
      </el-col>
      <el-col v-else :span="20">
        <el-empty description="暂无文件"/>
      </el-col>
    </el-row>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="query.page" :limit.sync="query.limit" :page-sizes="pageSizes" @pagination="list"/>
    <!-- 选择文件 -->
    <el-row v-show="fileType">
      <el-col style="text-align:right; margin-top:20px">
        <el-button @click="fileCancel()">取消</el-button>
        <el-button type="primary" @click="fileSubmit(checkedIds)">确定</el-button>
      </el-col>
    </el-row>

    <el-dialog class="video-dialog" :title="videoDialog.title" :visible.sync="videoDialog.visible" top="10vh" append-to-body :close-on-click-modal="false">
      <div class="video-modal">
        <video class="video-box" autoplay="autoplay" controls="controls">
          <source :src="videoDialog.file_url" type="video/mp4">
          <object :data="videoDialog.file_url" width="100%" height="100%">
            <embed :src="videoDialog.file_url" width="100%" height="100%">
          </object>
        </video>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import screenHeight from '@/utils/screen-height'
import Pagination from '@/components/Pagination/index'
import permission from '@/directive/permission' // 权限判断指令
import {getAdminToken} from '@/utils/auth'
import {uploadURL} from '@/api/admin/common'
import {list, info, save, del, disable} from '@/api/admin/file'

export default {
  name: 'FileManage',
  components: {Pagination},
  directives: {permission},
  props: {
    folder: {type: String, default: ''},
    fileType: {type: String, default: ''}
  },
  data() {
    return {
      name: '文件',
      height: 680,
      loadup: false,
      loading: false,
      query: {
        page: 1,
        limit: 18,
        folder: '',
        file_type: ''
      },
      pageSizes: [18, 24, 30, 50, 100],
      datas: [],
      total: 0,
      model: {
        id: '',
        name: '',
        file_url: '',
        full_file_url: '',
        file_type: '',
        file_size: '',
        file_ext: '',
        folder: '',
        storage: '',
        sorting: 10,
        status: 1
      },
      folders: [],
      fileTypes: [],
      storages: [],

      checkIds: [],
      checkAll: false,
      checkAllInd: false,
      checkedIds: [],

      uploadAction: uploadURL(),
      uploadHeaders: {AdminToken: getAdminToken()},
      uploadData: {},
      uploadLimit: 9,
      uploadFilelist: [],

      videoDialog: {
        visible: false,
        title: '查看视频',
        file_url: ''
      }
    }
  },
  watch: {
    'fileType': function (val, oldval) {
      this.query.folder = this.folder
      this.query.file_type = this.fileType
      this.list()
    }
  },
  created() {
    if (this.folder) {
      this.query.folder = this.folder
    }
    if (this.fileType) {
      // 弹出层中打开
      this.query.file_type = this.fileType
      this.height = screenHeight() - 250
    } else {
      this.height = screenHeight()
    }
    this.list()
  },
  methods: {
    // 列表
    list() {
      this.loading = true
      list(this.query).then(res => {
        this.datas = res.data.data
        this.total = res.data.total
        this.checkIds = res.data.ids
        this.folders = res.data.folders
        this.fileTypes = res.data.file_types
        this.storages = res.data.storages
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 删除
    del(row) {
      if (row.length === 0) {
        this.selectAlert()
      } else {
        var title = '删除' + this.name
        var message = '确定要删除选中的 <span style="color:red">' + row.length + ' </span> 个' + this.name + '吗？'
        if (row.length === 1) {
          title = title + '：' + row[0]
          message = '确定要删除' + this.name + '吗？'
        }
        this.$confirm(message, title, {type: 'warning', dangerouslyUseHTMLString: true}).then(() => {
          this.loading = true
          del({
            ids: row
          }).then(res => {
            this.list()
            this.reset()
            this.$message.success(res.msg)
          }).catch(() => {
            this.loading = false
          })
        }).catch(() => {
        })
      }
    },
    // 重置
    reset(row) {
      if (row) {
        this.model = row
      } else {
        this.model = this.$options.data().model
      }
      this.folder = ''
      this.checkedIds = []
      this.checkAll = false
      this.checkAllInd = false
      if (this.$refs['ref'] !== undefined) {
        this.$refs['ref'].resetFields()
      }
    },
    // 查询
    search() {
      this.query.page = 1
      this.list()
    },
    // 刷新
    refresh() {
      this.query = this.$options.data().query
      this.list()
    },
    // 启用/禁用
    isActivate(row, is_disable) {
      if (row.length === 0) {
        this.selectAlert()
      } else {
        if (is_disable === 0) {
          this.$confirm('禁用文件会对已使用该文件的业务造成影响！<br>确定要禁用文件吗？', '禁用文件', {type: 'warning', dangerouslyUseHTMLString: true}
          ).then(() => {
            this.loading = true
            disable({
              ids: row,
              status: is_disable
            }).then(res => {
              this.list()
              this.reset()
              this.$message.success(res.msg)
            }).catch(() => {
              this.list()
              this.loading = false
            })
          }).catch(() => {
          })
        } else {
          this.loading = true
          disable({
            ids: row,
            status: is_disable
          }).then(res => {
            this.list()
            this.reset()
            this.$message.success(res.msg)
          }).catch(() => {
            this.list()
            this.loading = false
          })
        }
      }
    },

    // 筛选切换
    filterSelect(folder = '', type = '') {
      this.query.folder = folder
      this.query.file_type = type
      this.uploadData.folder = folder
      this.list()
    },

    // 全选操作 -- 自定义按钮
    selectAll(val) {
      this.checkedIds = val ? this.checkIds : []
      this.checkAllInd = false
    },
    // 选择文件
    selectGroup(vals) {
      const checkedCount = vals.length
      this.checkAll = checkedCount === this.checkIds.length
      this.checkAllInd = checkedCount > 0 && checkedCount < this.checkIds.length
    },
    selectAlert(message = '') {
      this.$alert(message || '请选择需要操作的' + this.name, '提示', {
        confirmButtonText: '确定', callback: action => {
        }
      })
    },
    // 批量删除
    batchDel(row) {
      this.del(row)
    },

    // 上传文件
    uploadBefore() {
      this.loadup = true
    },
    uploadSuccess(res) {
      if (res.code === 200) {
        this.refresh()
        this.$message.success(res.msg)
      } else {
        this.$message.error(res.msg)
      }
      this.loadup = false
    },
    uploadError(res) {
      this.$message.error(res.msg || '上传出错')
      this.loadup = false
    },
    uploadChange() {
    },
    uploadExceed() {
      this.$message.error(`每次最多选择 ${this.uploadLimit} 个文件`)
    },
    uploadClear() {
      this.uploadFilelist = []
    },

    // 文件取消
    fileCancel() {
      this.checkedIds = []
      this.$emit('fileCancelCallback')
    },
    // 文件确定
    fileSubmit(row) {
      if (!row.length) {
        this.selectAlert('请选择文件')
      } else {
        const files = []
        const datas = this.datas
        const data_len = datas.length
        const row_len = row.length
        for (let i = 0; i < data_len; i++) {
          for (let j = 0; j < row_len; j++) {
            if (datas[i].id === row[j]) {
              files.push(datas[i])
            }
          }
        }
        this.checkedIds = []
        this.$emit('fileSubmitCallback', files, this.fileType)
      }
    },

    // 查看视频文件
    viewVideo(row) {
      this.videoDialog.visible = true
      this.videoDialog.file_url = row
    }
  }
}
</script>

<style scoped>
.item {
  margin-bottom: 5px;
}
.file-card {
  position: relative;
  overflow: hidden;
  background: #fff;
}

.file-ext {
  position: absolute;
  width: 100px;
  height: 100px;
  top: -66px;
  right: -66px;
  transform: rotate(45deg);
  z-index: 1000;
}

.file-ext span {
  display: block;
  position: absolute;
  width: 100px;
  bottom: 0;
  text-align: center;
  font-size: 14px;
  color: #fff;
  background: #C0C4CC;
}
</style>
